var http = require("http");
var url = require("url");
var path = require('path');
require("./dbase/db");


function start(route, handle) {

	function onRequest(request, response) {
	    var pathname = url.parse(request.url).pathname;
	    console.log("Request for " + pathname + " received.");
	    console.log('request starting...');
	
		var filePath = '.' + request.url;
		if (filePath == './')
			filePath = './view/start.html';
		
		var extname = path.extname(filePath);
		var contentType = 'text/html';
		switch (extname) {
			case '.js':
				contentType = 'text/javascript';
				pathname = '/js';
				break;
			case '.css':
				contentType = 'text/css';
				pathname = '/css';
				break;
			case '.htm':
			case '.html':
				contentType = 'text/html';
				pathname = '/htm';
			break;	
				
		}
	    console.log("filePath = "+filePath);
	    console.log("pathname = "+pathname);
        if (extname === 'css' || extname === 'html') {
			path.exists(filePath, function(exists) {
				if (exists) {
					console.log("handle[pathname] = "+handle[pathname]);
			      route(handle, pathname, response, request);
			    } else {
	              response.writeHead(404);
				  response.end();
			    }
			});
	    } else {
	    	route(handle, pathname,response,request);
	    }
    }
	console.log("----------------");
	dbase = new Database('nodenode', 'root', 'mysql', 'mysql', 3306);
	dbase.auth();
	console.log("Connection with DB was opened.")
	http.createServer(onRequest).listen(8888);
	console.log("Server has started.");
}

exports.start = start;